import React, {FC, useState} from "react";
import {Table} from "antd";
import {message, Popconfirm} from "_antd@4.20.5@antd";
import PopUpBox from "./PopUpBox";

const MyTable: FC<any> = ({title, operate, dataSource, handleOk}: any) => {
    // 弹出框是否显示
    const show = useState<boolean>(false);
    // 表头
    const columns: any = title.map((item: any) => ({
        title: item.title,
        dataIndex: item.dataIndex,
        key: item.dataIndex,
        width: 'auto',
    }))

    // 如果不传递操作方法则删除操作
    if (Object.values(operate).some(item => item)) {
        columns.push({
            title: '操作',
            key: 'operate',
            width: '200px',
            render: (text: any, record: any) => {
                return (
                    <div style={{color: "#409eff"}}>
                        {
                            operate.change && (
                                <span style={{margin: "0 10px", cursor: "pointer"}} onClick={() => {
                                    show[1](true)
                                    // 修改
                                    operate.change && operate.change(record)
                                }}>修改</span>
                            )
                        }
                        {
                            operate.delete && (
                                <Popconfirm
                                    title="确定要删除吗?"
                                    onConfirm={() => {
                                        // 删除 把数据传递到组件外
                                        operate.delete && operate.delete(record)
                                    }}
                                >
                                    <span style={{margin: "0 10px", cursor: "pointer"}}>删除</span>
                                </Popconfirm>
                            )
                        }
                    </div>
                )
            }
        })
    }
    // 弹出框表单
    let formItem = title.map((item: any) => ({
        label: item.title,
        name: item.dataIndex,
        type: item.type,
        required: item.required, // 是否必填
        regular: item.regular, // 正则验证
        options: item.options, // 下拉选项
        onChange: item.onChange, // 回调函数
    }))

    return (
        <div>
            <Table dataSource={dataSource} columns={columns} sticky
                   pagination={{
                       pageSize: 8,
                       hideOnSinglePage: true,
                       responsive: true,
                       position: ["bottomCenter"],
                       showQuickJumper: true
                   }}/>
            <PopUpBox formItem={formItem} show={show} handleOk={(form: any, setIsModalVisible: any) => {
                handleOk(form, setIsModalVisible)
            }}></PopUpBox>
        </div>
    );
};

export default MyTable;